package com.reebake.ideal.servlet.core;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.spring.SpringUtil;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 响应体包装接口
 */
public interface ResponseBodyWrapper {

    public Object convert(Integer code, Object object);

    default public Object convert(Object object) {
        return  convert(null, object);
    }

    public void write(HttpServletResponse response, Object object);

    default void convertAndWrite(HttpServletResponse response, Object object) {
        convertAndWrite(response, null, object);
    }

    default void convertAndWrite(HttpServletResponse response, Integer code, Object object) {
        Object result = convert(code, object);
        write(response, result);
    }

    public static void wrapResponse(HttpServletResponse response, Object object) {
        wrapResponse(response, null, object);
    }

    public static void wrapResponse(HttpServletResponse response, Integer code, Object object) {
        ResponseBodyWrapper responseBodyWrapper = SpringUtil.getBean(ResponseBodyWrapper.class);
        if(ObjUtil.isNull(responseBodyWrapper)) {
            return;
        }
        responseBodyWrapper.convertAndWrite(response, code, object);
    }
}
